﻿using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace easyVal.ServerSide
{
    public static class DataAnnotationsValidationRunner
    {
        public static List<ErrorInfo> GetErrors(object instance)
        {
            IEnumerable<ErrorInfo> result =
                from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
                from attribute in prop.Attributes.OfType<ValidationAttribute>()
                where !attribute.IsValid(prop.GetValue(instance))
                select new ErrorInfo(prop.Name, attribute.ErrorMessage, instance);

            return new List<ErrorInfo>(result);
        }
    }
}